package com.lvwenguo.config;

import com.lvwenguo.shiro.UserRealm;
import com.lvwenguo.token.JwtFilter;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author lvwenguo
 * @Date 2021/4/3 9:51
 * @Version 1.0
 */
@Configuration
public class ShiroConfig {


    //3、ShiroFilterFactoryBean
    @Bean(name = "shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        /*
        * 添加shiro内置过滤器
        * anon:无需认证即可访问
        * authc:必须认证才可以访问
        * user:必须有功能  记住我 才可以访问
        * perms:拥有对某个资源的访问权限才可以访问
        * role:有用某个角权限才可以访问
        * */
        //过滤
        Map<String,String> chainDefinitionMap = new LinkedHashMap<>();
        //注意：先后顺序也会影响到是否经过过滤器
        chainDefinitionMap.put("/login","anon");
        chainDefinitionMap.put("/saveUser","anon");
        chainDefinitionMap.put("/**","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(chainDefinitionMap);

        //自定义过滤器
        Map<String, Filter> filterMap = new LinkedHashMap<>();
        //这里key是jwt,这里是上面注册的名称
        filterMap.put("authc", new JwtFilter());
        shiroFilterFactoryBean.setFilters(filterMap);

        return shiroFilterFactoryBean;

    }


    //2、defaultWebSecurityManager
    @Bean(name = "defaultWebSecurityManager")
    public DefaultWebSecurityManager getdefaultSecurityManager(UserRealm userRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //关联realm
        defaultWebSecurityManager.setRealm(userRealm);


        return defaultWebSecurityManager;
    }

    //1、创建realm类，
    @Bean(name = "userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }
}
